package com.ccys.common.util.easyExcel;

import com.alibaba.excel.metadata.Head;
import com.alibaba.excel.write.merge.AbstractMergeStrategy;
import org.apache.commons.collections.CollectionUtils;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.util.CellRangeAddress;

import java.util.ArrayList;
import java.util.List;

/**
 * 合并策略
 */
public class MergeStrategy extends AbstractMergeStrategy {
    //合并坐标集合
    private List<CellRangeAddress> cellRangeAddressList;
    private boolean merge = true;
    //构造
    public MergeStrategy(List<Integer[]> list) {
        List<CellRangeAddress> data = new ArrayList<>();
        for (Integer[] arr : list) {
            //firstRow lastRow firstCol lastCol
            CellRangeAddress item = new CellRangeAddress(arr[0], arr[1], arr[2], arr[3]);
            data.add(item);
        }

        this.cellRangeAddressList = data;
    }

    /**
     * merge
     * @param sheet
     * @param cell
     * @param head
     * @param relativeRowIndex
     */
    @Override
    protected void merge(Sheet sheet, Cell cell, Head head, Integer relativeRowIndex) {
        //合并单元格
        if (CollectionUtils.isNotEmpty(cellRangeAddressList)&&merge) {
            for (CellRangeAddress item : cellRangeAddressList) {
                sheet.addMergedRegionUnsafe(item);
            }
            merge=false;
        }
    }
}
